package recallin.activities;

import java.util.ArrayList;
import java.util.Collections;

import org.mapsforge.android.maps.MapActivity;
import org.mapsforge.android.maps.overlay.ItemizedOverlay;
import org.mapsforge.android.maps.overlay.OverlayItem;
import org.mapsforge.core.GeoPoint;

import recallin.database.Friends;
import recallin.database.ServerConnection;
import recallin.gui.FriendsAdapter;
import android.R.layout;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.User;

/**
 * 
 * @author philipmasek
 * Handles all friends connection. Displays and locates friends via a db4o connection.
 */

@SuppressWarnings("static-access")
public class FriendsActivity extends Activity {

	private ListView listView;
	private ArrayList<Friends> list = new ArrayList<Friends>();
	private Thread thread;
	private Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends_menu);
		listView = (ListView) findViewById(R.id.friends_list_view);
		listView.setEmptyView(findViewById(R.id.empty_view2));
		mHandler = new Handler();
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					updateList(listView);
				} else if (msg.what == 1) {
					updateList(listView, list);
				}
				super.handleMessage(msg);
			}
		};
		updateList(listView);
		thread = new Thread() {
			boolean running = true;

			@Override
			public void run() {
				try {
					MenuActivity.connection.syncFriends();
					handler.sendEmptyMessage(0);
				} catch (NullPointerException e) {
					Log.d("SyncFriends", "Connection problems");
				}
				super.run();
			}

		};
		thread.start();

		EditText searchField = (EditText) findViewById(R.id.friends_search_field);
		MenuActivity.setupSearchField(this, searchField);

		listView.requestFocus();
		listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listView.requestFocus();
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				openContextMenu(arg1);

			}
		});

		searchField.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(final CharSequence s, int start,
					int before, int count) {
				Thread thread1 = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							list = new ArrayList<Friends>(MenuActivity.connection
									.searchUsers(s.toString()));
							handler.sendEmptyMessage(1);
						} catch (NullPointerException e) {
							Log.d("SearchingFriends", "Connection problems");
						}
					}
				});
				((FriendsAdapter) listView.getAdapter()).getFilter()
						.filter(s);
				if (s.toString().length() > 3) {
					thread1.start();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		listView.requestFocus();


		registerForContextMenu(listView);
	}

	@Override
	public void onPause() {
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		super.onPause();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.friends_list_view) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			menu.setHeaderTitle(((FriendsAdapter) listView.getAdapter())
					.getItem(info.position).getName());
			String[] menuItems = getResources().getStringArray(R.array.menu);
			for (int i = 0; i < menuItems.length; i++) {
				menu.add(0, i, i, menuItems[i]);
			}
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		String[] menuItems = getResources().getStringArray(R.array.menu);
		String menuItemName = menuItems[menuItemIndex];
		final Friends listItemName = ((FriendsAdapter) listView
				.getAdapter()).getItem(info.position);

		switch (menuItemIndex) {
		case 0:
			OverlayItem overlayItem = new OverlayItem(new GeoPoint(listItemName.getLatitude(), listItemName.getLongitude()), listItemName.getName(), "");
			overlayItem.setMarker(ItemizedOverlay.boundCenterBottom(getResources().getDrawable(R.drawable.pin)));
			MainActivity.addOverlayItem(overlayItem);
			finish();
			break;
		case 1:
			if (listItemName.getMe_hidden()==0) {
				MenuActivity.connection.toggleFriendVisibility(listItemName.getUser_id(), false);
				ObjectContainer db = Db4oEmbedded
						.openFile(ServerConnection.DB4OFILENAME);
				try{
					db.delete(listItemName);
					listItemName.setMe_hidden(1);
					listItemName.setStatus(Friends.CHANGED);
					db.store(db);
				}finally{
					db.close();
				}
			}else{
				MenuActivity.connection.toggleFriendVisibility(listItemName.getUser_id(), false);
				ObjectContainer db = Db4oEmbedded
						.openFile(ServerConnection.DB4OFILENAME);
				try{
					db.delete(listItemName);
					listItemName.setMe_hidden(0);
					listItemName.setStatus(Friends.CHANGED);
					db.store(db);
				}finally{
					db.close();
				}
			}
			break;
		case 2:
			AlertDialog.Builder adb = new AlertDialog.Builder(
					FriendsActivity.this);
			adb.setTitle("Remove?");
			adb.setMessage("Are you sure you want to remove "
					+ listItemName.getName() + "?");
			final int position = info.position;
			adb.setNegativeButton("Cancel", null);
			adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					ObjectContainer db = Db4oEmbedded
							.openFile(ServerConnection.DB4OFILENAME);
					try {
						for (Friends friend : db.query(Friends.class)) {
							if (((FriendsAdapter) listView.getAdapter())
									.getItem(position).getUser_id() == friend
									.getUser_id()) {
								db.delete(friend);
								((FriendsAdapter) listView.getAdapter())
										.getItem(position).setStatus(
												Friends.DELETED);
								db.store(((FriendsAdapter) listView
										.getAdapter()).getItem(position));
							}
						}
					} finally {
						db.close();
					}
					Thread thread = new Thread(new Runnable() {
						@Override
						public void run() {
							updateList(listView);
						}
					});
					thread.start();
				}
			});
			adb.show();
			break;

		default:
			break;
		}
		
		
		
		return true;
	}

	private void updateList(final ListView listView) {
		ArrayList<Friends> information = new ArrayList<Friends>();
		ObjectContainer db = Db4oEmbedded
				.openFile(ServerConnection.DB4OFILENAME);
		try {
			for (Friends friend : db.query(Friends.class)) {
				if (friend.getStatus() != Friends.DELETED) {
					friend.setAvatarId(R.drawable.ic_launcher);
					information.add(friend);
				}
			}
			Collections.sort(information);
			final FriendsAdapter adapter = new FriendsAdapter(
					getApplicationContext(),
					android.R.layout.simple_list_item_1, information);
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					listView.setAdapter(adapter);
				}
			});
		} finally {
			db.close();
		}
	}

	private void updateList(ListView listView, ArrayList<Friends> people) {
		FriendsAdapter adapter = new FriendsAdapter(this,
				layout.simple_list_item_1, people);
		listView.setAdapter(adapter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
